package edu.mobbuzz.web.pages;


import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;

import edu.mobbuzz.daf.bean.User;
import edu.mobbuzz.web.base.SecureBasePage;
import edu.mobbuzz.web.facade.ManagementFacade;

public class ChangePasswordFormPage extends SecureBasePage{
	@Property
	private String currentPassword;
	@Property
	private String newPassword;
	@Property
	private String renewPassword;
	
	private String username;
	@Property
	private User user;
	private ManagementFacade managamentFacade;
	
	@Component
	private Form passwordForm;
	
	void onActionFromClear(){
		passwordForm.clearErrors();
    }
	
	Object onSuccessFromPasswordForm(){
		if(user.getPassword().equals(currentPassword)){
			if(newPassword.equals(renewPassword)){
				user.setPassword(newPassword);
				getManagamentFacade().updateUser(user);
				return UserGridPage.class;
			}else{
				passwordForm.recordError("password didn't match");
				return null;
			}
		}else{
			passwordForm.recordError("wrong password");
			return null;
		}
		
	}
	
	void onActivate(String username){
		this.username = username;
		user = getManagamentFacade().getUserByPrimaryKey(username);	
	}
	
	String onPassivate(){ 
		return username;
	}	
	
	public ManagementFacade getManagamentFacade() {
		if(managamentFacade==null){
			managamentFacade = new ManagementFacade();
		}
		return managamentFacade;
	}
	
}
